//
//  YSUserInfoViewController.m
//  Yaoyle
//
//  Created by ZhaoXudong on 14-9-24.
//  Copyright (c) 2014年 ZhaoXudong. All rights reserved.
//

#import "YSUserInfoViewController.h"
#import "YSChangePwdViewController.h"
#import "YSRechargeViewController.h"
#import "YSAppDelegate.h"
#import "YSImagePickerViewController.h"
#import "ASIFormDataRequest.h"
#import "NSData+AES256.h"
#import "JSONKit.h"

@interface YSUserInfoViewController () <UIActionSheetDelegate, UIImagePickerControllerDelegate> {
    
    __weak IBOutlet UIImageView *userHeadImage;
    __weak IBOutlet UILabel *userName;
    __weak IBOutlet UILabel *userScore;
    __weak IBOutlet UILabel *userSex;
}

@end

@implementation YSUserInfoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [UIImageView roundImage:userHeadImage];
    
    userName.text = [NSString stringWithFormat:@"用户昵称:%@",_userModel.name];
    NSString *sexStr;
    if (_userModel.sex == eSexBoy) {
        sexStr = @"性别: 男";
    } else {
        sexStr = @"性别: 女";
    }
    
    if (![YSUtility isBlankObject:_userModel.photoUrl]) {
        double delayInSeconds = 0.1;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:_userModel.photoUrl]];
            userHeadImage.image = [UIImage imageWithData:data];
        });
    }
    [self reloadUserScore];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -

- (void)reloadUserScore {
    userScore.text = [NSString stringWithFormat:@"幸运豆:%@",_userModel.scoreAmount];
}

- (IBAction)changeUserHeadImage:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"从图片库中选取", nil];
    
    [actionSheet showInView:[UIApplication sharedApplication].keyWindow];
    [actionSheet showInView:self.view];
}

- (IBAction)exitLogin:(id)sender {
    [_userModel logout];
    _userModel = nil;
    [self.navigationController popViewControllerAnimated:NO];
}

- (IBAction)changePassword:(id)sender {
    YSChangePwdViewController *changePwdVC = [[YSChangePwdViewController alloc] initWithNibName:@"YSChangePwdViewController"
                                                                                         bundle:nil];
    [self.navigationController pushViewController:changePwdVC animated:YES];
}

- (IBAction)gotoRecharge:(id)sender {
    YSRechargeViewController *rechargeVC = [[YSRechargeViewController alloc] initWithNibName:@"YSRechargeViewController"
                                                                                      bundle:nil];
    rechargeVC.blcok = ^(NSInteger value){
        NSInteger temp = [_userModel.scoreAmount intValue];
        _userModel.scoreAmount = [NSString stringWithFormat:@"%d",temp + value];
        [self reloadUserScore];
    };
    [self.navigationController pushViewController:rechargeVC animated:YES];
}

- (IBAction)back:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark- 缩放图片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *resultImage = [info objectForKey:UIImagePickerControllerEditedImage];
    userHeadImage.image = resultImage;
    
    
    NSMutableString *urlParams = [[NSMutableString alloc] initWithCapacity:128];
    
    [urlParams appendFormat:@"%@/upload.do?", HTTP_SERVER_URL];
    
    [urlParams appendString:[NSString stringWithFormat:@"uid=%@", [YSGlobal getUID]]];
    
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlParams]];
    request.tag = 1000;
    
    NSString *imagePath = [self zipImage:resultImage];
    
    [request setFile:imagePath forKey:@"file"];

    [request setRequestMethod:@"POST"];
    [request setTimeOutSeconds:60];
    [request buildPostBody];
    [request setDelegate:self];
    [request startAsynchronous];
}

- (void)requestFinished:(ASIHTTPRequest *)request{
    if (request.tag == 1000) {
        NSString *returnString = [[NSString alloc] initWithData:request.responseData encoding:NSUTF8StringEncoding];
        NSString *responseStr = [NSData AES256DecryptWithCiphertextExt:returnString];
        NSDictionary *responseDict = [responseStr objectFromJSONString];
        NSDictionary *re = [responseDict objectForKey:@"re"];
        
        _userModel.photoUrl = re[@"url"];
        [_userModel saveUserInfo];
    }
}

-(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    float fWidth = 82;
    float fHeight = 82;
    
    UIGraphicsBeginImageContext(CGSizeMake(fWidth,fHeight));
    [image drawInRect:CGRectMake(0, 0, fWidth,fHeight)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

- (NSString *)zipImage:(UIImage *)image {
    
    UIImage *scaleImage = [self scaleImage:image toScale:0.3];
    
    NSData *data;
    
    if (UIImagePNGRepresentation(scaleImage) == nil) {
        //将图片转换为JPG格式的二进制数据
        data = UIImageJPEGRepresentation(scaleImage, 1);
    } else {
        //将图片转换为PNG格式的二进制数据
        data = UIImagePNGRepresentation(scaleImage);
    }
    
    NSFileManager *fileManager = [NSFileManager defaultManager];//将图片存储到本地documents
    NSString *filePath = [[NSHomeDirectory() stringByAppendingString:@"/Documents"] stringByAppendingString:@"/imgs"];
    BOOL isExist = [fileManager fileExistsAtPath:filePath];
    if (!isExist) {
        [fileManager createDirectoryAtPath:filePath
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:nil];
    }
    BOOL isImage = [fileManager createFileAtPath:[filePath stringByAppendingString:@"/commentImage.png"] contents:data attributes:nil];
    if (isImage) {
        return [filePath stringByAppendingString:@"/commentImage.png"];
    }
    
    return nil;
}
#pragma mark - UIActionSheet
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != [actionSheet cancelButtonIndex]) {
        NSInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
//            sourceType = UIImagePickerControllerSourceTypeCamera;
//        }
//        
//        if (buttonIndex == 1) {
//            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//        }
        
        YSImagePickerViewController *imagePickerVC = [[YSImagePickerViewController alloc] init];
        imagePickerVC.sourceType = sourceType;
        imagePickerVC.delegate = self;
        imagePickerVC.allowsEditing = YES;
        [self presentViewController:imagePickerVC animated:YES completion:nil];
    }
}

#pragma mark - 
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation ==  UIInterfaceOrientationLandscapeLeft ||
            interfaceOrientation ==  UIInterfaceOrientationLandscapeRight );
}

-(NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscape;
}

- (BOOL)shouldAutorotate {
    return YES;
}
@end
